//
//  ReceiptController.m
//  Gekko
//
//  Created by jose on 13/07/13.
//  Copyright (c) 2013 Jose Luis Lopez. All rights reserved.
//

#import "ReceiptController.h"

static ReceiptController *sharedInstance;

@implementation ReceiptController

@synthesize delegate;

+(ReceiptController *)shared {

    if(sharedInstance == nil) {
        sharedInstance = [[ReceiptController alloc] init];
    }
    
    return sharedInstance;
}

- (void)uploadReceipt:(Receipt *)receipt {
//    NSURLRequest *request = [TDOAuth URLRequestForPath:nApiListBrands GETParameters:nil host:nApiBaseUrl consumerKey:ConsumerKey consumerSecret:ConsumerSecret accessToken:AccessToken tokenSecret:AccessTokenSecret];
    
    // Cost type
    NSString *costType;
    if ([receipt.costType isEqualToString:NSLocalizedString(@"COST 0", nil)]) {
        costType = @"material";
    } else if ([receipt.costType isEqualToString:NSLocalizedString(@"COST 1", nil)]) {
        costType = @"car";
    } else if ([receipt.costType isEqualToString:NSLocalizedString(@"COST 2", nil)]) {
        costType = @"travel";
    } else if ([receipt.costType isEqualToString:NSLocalizedString(@"COST 3", nil)]) {
        costType = @"represent";
    } else if ([receipt.costType isEqualToString:NSLocalizedString(@"COST 4", nil)]) {
        costType = @"food";
    } else if ([receipt.costType isEqualToString:NSLocalizedString(@"COST 5", nil)]) {
        costType = @"admin";
    } else if ([receipt.costType isEqualToString:NSLocalizedString(@"COST 6", nil)]) {
        costType = @"office";
    } else if ([receipt.costType isEqualToString:NSLocalizedString(@"COST 7", nil)]) {
        costType = @"other";
    }
    
    // Total amount
    NSString *totalAmount = [receipt.totalAmount stringByReplacingOccurrencesOfString:@"," withString:@"."];
    
    // Date
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *date = [formatter stringFromDate:receipt.date];
    
    // Other params treatment
    
    // Params
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                             @"3", @"owner_company",
                            totalAmount, @"amount",
                            receipt.description, @"description",
                            costType, @"cost_type",
                            date, @"date",
                            @"", @"image",
                             nil];

    NSLog(@"Uploading the receipt with params: %@", params);
    
    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:kAPIUploadReceipt]];
    [client registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [client setDefaultHeader:@"Accept" value:@"application/json"];
    client.parameterEncoding = AFJSONParameterEncoding;

    NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:nil parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        
        [formData appendPartWithFileData:UIImageJPEGRepresentation(receipt.image, 0.5) name:@"image" fileName:@"image.png" mimeType:@"image/jpeg"];
    }];
        
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        NSLog(@"Response: %@", JSON);
        
        [self markReceipt:receipt as:kStatusUploaded];
        
        if ([delegate respondsToSelector:@selector(uploadSuccededWithId:)]) 
            [delegate performSelector:@selector(uploadSuccededWithId:) withObject:receipt.idi];
        
        
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

        NSLog(@"Request failed: %@", [error userInfo]);
        
        [self markReceipt:receipt as:kStatusReady];
        
        if ([delegate respondsToSelector:@selector(uploadFailedWithId:)])
            [delegate performSelector:@selector(uploadFailedWithId:) withObject:receipt.idi];
    }];
    
    [operation start];
}

-(void)markReceipt:(Receipt *)receipt as:(NSString *)status {
    
    receipt.status = status;
    
    NSInteger foundedAtIndex = -1;
    for (int i = 0; i < [[ReceiptsHolder sharedReceiptsHolder].arrayReceipts count]; i ++) {
        
        if ([((Receipt *) [[ReceiptsHolder sharedReceiptsHolder].arrayReceipts objectAtIndex:i]).idi
             isEqualToString:receipt.idi]) {
            foundedAtIndex = i;
            break;
        }
    }
    
    if (foundedAtIndex == - 1)
        [[ReceiptsHolder sharedReceiptsHolder].arrayReceipts insertObject:receipt atIndex:0];
    else
        [[ReceiptsHolder sharedReceiptsHolder].arrayReceipts replaceObjectAtIndex:foundedAtIndex withObject:receipt];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [ArchiverUnarchiver archiveReceipt:receipt];
    });
    
    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:kKeyShoudReload];
}

@end
